<template>
  <div class="salesperson-stats">
    <el-card class="box-card">
      <!-- 筛选条件 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item label="统计时间">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="所属部门">
            <el-select v-model="filterForm.department" placeholder="请选择部门">
              <el-option label="全部" value=""></el-option>
              <el-option label="电子产品部" value="electronics"></el-option>
              <el-option label="服装部" value="clothing"></el-option>
              <el-option label="食品部" value="food"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据概览 -->
      <div class="stats-overview">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div slot="header" class="clearfix">
                <span>总销售额</span>
              </div>
              <div class="stats-value">¥{{ overview.totalSales.toFixed(2) }}</div>
              <div class="stats-compare" :class="{ 'up': overview.salesGrowth > 0, 'down': overview.salesGrowth < 0 }">
                较上期{{ Math.abs(overview.salesGrowth) }}%
                <i :class="overview.salesGrowth > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div slot="header" class="clearfix">
                <span>订单数量</span>
              </div>
              <div class="stats-value">{{ overview.totalOrders }}</div>
              <div class="stats-compare" :class="{ 'up': overview.ordersGrowth > 0, 'down': overview.ordersGrowth < 0 }">
                较上期{{ Math.abs(overview.ordersGrowth) }}%
                <i :class="overview.ordersGrowth > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div slot="header" class="clearfix">
                <span>新增客户</span>
              </div>
              <div class="stats-value">{{ overview.newCustomers }}</div>
              <div class="stats-compare" :class="{ 'up': overview.customersGrowth > 0, 'down': overview.customersGrowth < 0 }">
                较上期{{ Math.abs(overview.customersGrowth) }}%
                <i :class="overview.customersGrowth > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div slot="header" class="clearfix">
                <span>目标完成率</span>
              </div>
              <div class="stats-value">{{ overview.targetCompletion }}%</div>
              <el-progress 
                :percentage="overview.targetCompletion" 
                :status="overview.targetCompletion >= 100 ? 'success' : ''"
              ></el-progress>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 销售趋势图 -->
      <div class="sales-trend">
        <div class="chart-title">销售趋势</div>
        <div class="chart-container" ref="salesChart"></div>
      </div>

      <!-- 业绩排行 -->
      <div class="performance-ranking">
        <div class="section-header">
          <span class="title">业绩排行</span>
          <el-radio-group v-model="rankingType" size="small">
            <el-radio-button label="sales">销售额</el-radio-button>
            <el-radio-button label="orders">订单数</el-radio-button>
            <el-radio-button label="customers">新客户</el-radio-button>
          </el-radio-group>
        </div>
        <el-table
          :data="rankingList"
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="排名" width="80"></el-table-column>
          <el-table-column prop="name" label="销售员" width="120"></el-table-column>
          <el-table-column prop="department" label="所属部门" width="120">
            <template slot-scope="scope">
              {{ getDepartmentText(scope.row.department) }}
            </template>
          </el-table-column>
          <el-table-column :label="getRankingLabel" width="150">
            <template slot-scope="scope">
              <span v-if="rankingType === 'sales'">¥{{ scope.row.sales.toFixed(2) }}</span>
              <span v-else>{{ scope.row[rankingType] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="targetCompletion" label="目标完成率" width="200">
            <template slot-scope="scope">
              <el-progress 
                :percentage="scope.row.targetCompletion"
                :status="scope.row.targetCompletion >= 100 ? 'success' : ''"
              ></el-progress>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getSalespersonStats } from '@/api/salespeople'
import * as echarts from 'echarts'

export default {
  name: 'SalespersonStats',
  data() {
    return {
      // 筛选表单
      filterForm: {
        dateRange: [],
        department: ''
      },
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 数据概览
      overview: {
        totalSales: 1000000,
        salesGrowth: 15.8,
        totalOrders: 1200,
        ordersGrowth: 8.5,
        newCustomers: 150,
        customersGrowth: -3.2,
        targetCompletion: 85
      },
      // 排行榜类型
      rankingType: 'sales',
      // 排行榜数据
      rankingList: [
        {
          name: '张三',
          department: 'electronics',
          sales: 300000,
          orders: 100,
          customers: 30,
          targetCompletion: 95
        },
        {
          name: '李四',
          department: 'clothing',
          sales: 250000,
          orders: 80,
          customers: 25,
          targetCompletion: 85
        }
      ],
      // 图表实例
      salesChart: null
    }
  },
  computed: {
    getRankingLabel() {
      const labelMap = {
        sales: '销售额',
        orders: '订单数',
        customers: '新客户数'
      }
      return labelMap[this.rankingType]
    }
  },
  mounted() {
    this.initChart()
    this.fetchData()
  },
  beforeDestroy() {
    if (this.salesChart) {
      this.salesChart.dispose()
    }
  },
  methods: {
    // 获取部门文本
    getDepartmentText(department) {
      const departmentMap = {
        electronics: '电子产品部',
        clothing: '服装部',
        food: '食品部'
      }
      return departmentMap[department] || department
    },
    // 初始化图表
    initChart() {
      this.salesChart = echarts.init(this.$refs.salesChart)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['销售额', '订单数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            axisLabel: {
              formatter: '{value} 元'
            }
          },
          {
            type: 'value',
            name: '订单数',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            smooth: true,
            data: [150000, 180000, 120000, 200000, 160000, 220000, 190000]
          },
          {
            name: '订单数',
            type: 'line',
            smooth: true,
            yAxisIndex: 1,
            data: [50, 60, 45, 70, 55, 75, 65]
          }
        ]
      }
      this.salesChart.setOption(option)
      
      // 响应式调整
      window.addEventListener('resize', () => {
        this.salesChart.resize()
      })
    },
    // 获取数据
    async fetchData() {
      try {
        const params = {
          ...this.filterForm,
          startDate: this.filterForm.dateRange[0],
          endDate: this.filterForm.dateRange[1]
        }
        const res = await getSalespersonStats(params)
        // TODO: 更新数据和图表
      } catch (error) {
        console.error('获取统计数据失败：', error)
        this.$message.error('获取统计数据失败')
      }
    },
    // 筛选方法
    handleFilter() {
      this.fetchData()
    },
    resetFilter() {
      this.filterForm = {
        dateRange: [],
        department: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.salesperson-stats {
  .filter-container {
    margin-bottom: 20px;
  }

  .stats-overview {
    margin-bottom: 30px;

    .stats-card {
      .stats-value {
        font-size: 24px;
        font-weight: bold;
        margin: 10px 0;
      }

      .stats-compare {
        font-size: 14px;
        color: #909399;

        &.up {
          color: #67C23A;
        }

        &.down {
          color: #F56C6C;
        }

        i {
          margin-left: 5px;
        }
      }
    }
  }

  .sales-trend {
    margin-bottom: 30px;

    .chart-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
    }

    .chart-container {
      height: 400px;
    }
  }

  .performance-ranking {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .title {
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
}
</style> 